/**
 * 数据验证工具函数 - TypeScript版本
 * 提供身份证、密码强度、银行卡、手机号、邮箱等数据验证功能
 * 支持直接复制粘贴使用，无需任何依赖
 * 每个函数都是独立的，可以单独复制使用
 */

// 类型定义
export interface ValidationResult {
  isValid: boolean;
  message: string;
  [key: string]: any;
}

export interface IdCardInfo {
  year: number;
  month: number;
  day: number;
  gender: string;
  birthDate: string;
  age: number;
}

export interface IdCardResult extends ValidationResult {
  type: string;
  info?: IdCardInfo;
}

export interface PasswordResult extends ValidationResult {
  level: string;
  score: number;
  details: {
    length: number;
    hasUppercase: boolean;
    hasLowercase: boolean;
    hasNumbers: boolean;
    hasSpecialChars: boolean;
    hasForbiddenWords: boolean;
    matchesCustomPattern: boolean;
  };
}

export interface PasswordOptions {
  minLength?: number;
  maxLength?: number;
  requireUppercase?: boolean;
  requireLowercase?: boolean;
  requireNumbers?: boolean;
  requireSpecialChars?: boolean;
  forbiddenWords?: string[];
  customPattern?: RegExp;
}

export interface BankCardResult extends ValidationResult {
  cardType: string;
  maskedNumber?: string;
}

export interface PhoneResult extends ValidationResult {
  country: string;
  formatted?: string;
}

export interface EmailResult extends ValidationResult {
  domain?: string;
}

export interface UrlResult extends ValidationResult {
  protocol?: string;
  hostname?: string;
  pathname?: string;
}

export interface IpResult extends ValidationResult {
  version: string;
}

export interface PostalCodeResult extends ValidationResult {
  country: string;
}

export interface LicensePlateResult extends ValidationResult {
  country: string;
}

export interface BatchValidationResult {
  isValid: boolean;
  message: string;
  totalCount: number;
  validCount: number;
  invalidCount: number;
  results: Array<{
    index: number;
    value: any;
    result: ValidationResult;
  }>;
}

// 常量定义
export const VALIDATION_TYPES = {
  ID_CARD: 'idCard',
  PASSWORD: 'password',
  BANK_CARD: 'bankCard',
  PHONE: 'phone',
  EMAIL: 'email',
  URL: 'url',
  IP: 'ip',
  POSTAL_CODE: 'postalCode',
  LICENSE_PLATE: 'licensePlate'
} as const;

export const PASSWORD_LEVELS = {
  WEAK: 'weak',
  MEDIUM: 'medium',
  STRONG: 'strong',
  VERY_STRONG: 'very_strong'
} as const;

export const ID_CARD_TYPES = {
  CHINA_18: 'china_18',
  CHINA_15: 'china_15',
  TAIWAN: 'taiwan',
  HONG_KONG: 'hong_kong',
  MACAU: 'macau'
} as const;

/**
 * 验证身份证号码
 * @param {string} idCard - 身份证号码
 * @param {string} type - 身份证类型
 * @returns {IdCardResult} 验证结果
 */
export function validateIdCard(idCard: string, type: string = ID_CARD_TYPES.CHINA_18): IdCardResult {
  if (!idCard || typeof idCard !== 'string') {
    return {
      isValid: false,
      message: '身份证号码不能为空',
      type: type
    };
  }

  const cleanIdCard = idCard.trim().toUpperCase();
  
  switch (type) {
    case ID_CARD_TYPES.CHINA_18:
      return validateChina18IdCard(cleanIdCard);
    case ID_CARD_TYPES.CHINA_15:
      return validateChina15IdCard(cleanIdCard);
    case ID_CARD_TYPES.TAIWAN:
      return validateTaiwanIdCard(cleanIdCard);
    case ID_CARD_TYPES.HONG_KONG:
      return validateHongKongIdCard(cleanIdCard);
    case ID_CARD_TYPES.MACAU:
      return validateMacauIdCard(cleanIdCard);
    default:
      return {
        isValid: false,
        message: '不支持的身份证类型',
        type: type
      };
  }
}

/**
 * 验证中国大陆18位身份证
 * @param {string} idCard - 身份证号码
 * @returns {IdCardResult} 验证结果
 */
export function validateChina18IdCard(idCard: string): IdCardResult {
  // 18位身份证号码正则
  const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
  
  if (!idCardRegex.test(idCard)) {
    return {
      isValid: false,
      message: '身份证号码格式不正确',
      type: ID_CARD_TYPES.CHINA_18
    };
  }

  // 校验码验证
  const checkCode = idCard.charAt(17);
  const calculatedCheckCode = calculateIdCardCheckCode(idCard.substring(0, 17));
  
  if (checkCode !== calculatedCheckCode) {
    return {
      isValid: false,
      message: '身份证号码校验码不正确',
      type: ID_CARD_TYPES.CHINA_18
    };
  }

  // 提取信息
  const info = extractIdCardInfo(idCard);
  
  return {
    isValid: true,
    message: '身份证号码有效',
    type: ID_CARD_TYPES.CHINA_18,
    info: info
  };
}

/**
 * 验证中国大陆15位身份证
 * @param {string} idCard - 身份证号码
 * @returns {IdCardResult} 验证结果
 */
export function validateChina15IdCard(idCard: string): IdCardResult {
  // 15位身份证号码正则
  const idCardRegex = /^[1-9]\d{5}\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}$/;
  
  if (!idCardRegex.test(idCard)) {
    return {
      isValid: false,
      message: '身份证号码格式不正确',
      type: ID_CARD_TYPES.CHINA_15
    };
  }

  // 提取信息
  const info = extractIdCardInfo(idCard);
  
  return {
    isValid: true,
    message: '身份证号码有效',
    type: ID_CARD_TYPES.CHINA_15,
    info: info
  };
}

/**
 * 验证台湾身份证
 * @param {string} idCard - 身份证号码
 * @returns {IdCardResult} 验证结果
 */
export function validateTaiwanIdCard(idCard: string): IdCardResult {
  // 台湾身份证号码正则
  const idCardRegex = /^[A-Z][12]\d{8}$/;
  
  if (!idCardRegex.test(idCard)) {
    return {
      isValid: false,
      message: '台湾身份证号码格式不正确',
      type: ID_CARD_TYPES.TAIWAN
    };
  }

  return {
    isValid: true,
    message: '台湾身份证号码有效',
    type: ID_CARD_TYPES.TAIWAN
  };
}

/**
 * 验证香港身份证
 * @param {string} idCard - 身份证号码
 * @returns {IdCardResult} 验证结果
 */
export function validateHongKongIdCard(idCard: string): IdCardResult {
  // 香港身份证号码正则
  const idCardRegex = /^[A-Z]\d{6}\([0-9A]\)$/;
  
  if (!idCardRegex.test(idCard)) {
    return {
      isValid: false,
      message: '香港身份证号码格式不正确',
      type: ID_CARD_TYPES.HONG_KONG
    };
  }

  return {
    isValid: true,
    message: '香港身份证号码有效',
    type: ID_CARD_TYPES.HONG_KONG
  };
}

/**
 * 验证澳门身份证
 * @param {string} idCard - 身份证号码
 * @returns {IdCardResult} 验证结果
 */
export function validateMacauIdCard(idCard: string): IdCardResult {
  // 澳门身份证号码正则
  const idCardRegex = /^[1-9]\d{7}\([0-9A]\)$/;
  
  if (!idCardRegex.test(idCard)) {
    return {
      isValid: false,
      message: '澳门身份证号码格式不正确',
      type: ID_CARD_TYPES.MACAU
    };
  }

  return {
    isValid: true,
    message: '澳门身份证号码有效',
    type: ID_CARD_TYPES.MACAU
  };
}

/**
 * 计算身份证校验码
 * @param {string} idCard - 身份证号码前17位
 * @returns {string} 校验码
 */
export function calculateIdCardCheckCode(idCard: string): string {
  const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
  
  let sum = 0;
  for (let i = 0; i < 17; i++) {
    sum += parseInt(idCard.charAt(i)) * weights[i];
  }
  
  return checkCodes[sum % 11];
}

/**
 * 提取身份证信息
 * @param {string} idCard - 身份证号码
 * @returns {IdCardInfo|null} 身份证信息
 */
export function extractIdCardInfo(idCard: string): IdCardInfo | null {
  if (idCard.length === 18) {
    const year = parseInt(idCard.substring(6, 10));
    const month = parseInt(idCard.substring(10, 12));
    const day = parseInt(idCard.substring(12, 14));
    const gender = parseInt(idCard.charAt(16)) % 2 === 0 ? '女' : '男';
    
    return {
      year: year,
      month: month,
      day: day,
      gender: gender,
      birthDate: `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`,
      age: calculateAge(year, month, day)
    };
  } else if (idCard.length === 15) {
    const year = 1900 + parseInt(idCard.substring(6, 8));
    const month = parseInt(idCard.substring(8, 10));
    const day = parseInt(idCard.substring(10, 12));
    const gender = parseInt(idCard.charAt(14)) % 2 === 0 ? '女' : '男';
    
    return {
      year: year,
      month: month,
      day: day,
      gender: gender,
      birthDate: `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`,
      age: calculateAge(year, month, day)
    };
  }
  
  return null;
}

/**
 * 计算年龄
 * @param {number} year - 年份
 * @param {number} month - 月份
 * @param {number} day - 日期
 * @returns {number} 年龄
 */
function calculateAge(year: number, month: number, day: number): number {
  const today = new Date();
  const birthDate = new Date(year, month - 1, day);
  
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  
  return Math.max(0, age);
}

/**
 * 验证密码强度
 * @param {string} password - 密码
 * @param {PasswordOptions} options - 验证选项
 * @returns {PasswordResult} 验证结果
 */
export function validatePassword(password: string, options: PasswordOptions = {}): PasswordResult {
  const {
    minLength = 8,
    maxLength = 128,
    requireUppercase = true,
    requireLowercase = true,
    requireNumbers = true,
    requireSpecialChars = true,
    forbiddenWords = [],
    customPattern = null
  } = options;

  if (!password || typeof password !== 'string') {
    return {
      isValid: false,
      message: '密码不能为空',
      level: PASSWORD_LEVELS.WEAK,
      score: 0,
      details: {
        length: 0,
        hasUppercase: false,
        hasLowercase: false,
        hasNumbers: false,
        hasSpecialChars: false,
        hasForbiddenWords: false,
        matchesCustomPattern: false
      }
    };
  }

  const result: PasswordResult = {
    isValid: true,
    message: '密码有效',
    level: PASSWORD_LEVELS.WEAK,
    score: 0,
    details: {
      length: password.length,
      hasUppercase: false,
      hasLowercase: false,
      hasNumbers: false,
      hasSpecialChars: false,
      hasForbiddenWords: false,
      matchesCustomPattern: false
    }
  };

  let score = 0;

  // 长度检查
  if (password.length < minLength) {
    result.isValid = false;
    result.message = `密码长度不能少于${minLength}位`;
    return result;
  }

  if (password.length > maxLength) {
    result.isValid = false;
    result.message = `密码长度不能超过${maxLength}位`;
    return result;
  }

  // 长度得分
  score += Math.min(password.length * 2, 20);

  // 大写字母检查
  if (/[A-Z]/.test(password)) {
    result.details.hasUppercase = true;
    score += 10;
  } else if (requireUppercase) {
    result.isValid = false;
    result.message = '密码必须包含大写字母';
    return result;
  }

  // 小写字母检查
  if (/[a-z]/.test(password)) {
    result.details.hasLowercase = true;
    score += 10;
  } else if (requireLowercase) {
    result.isValid = false;
    result.message = '密码必须包含小写字母';
    return result;
  }

  // 数字检查
  if (/\d/.test(password)) {
    result.details.hasNumbers = true;
    score += 10;
  } else if (requireNumbers) {
    result.isValid = false;
    result.message = '密码必须包含数字';
    return result;
  }

  // 特殊字符检查
  if (/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) {
    result.details.hasSpecialChars = true;
    score += 15;
  } else if (requireSpecialChars) {
    result.isValid = false;
    result.message = '密码必须包含特殊字符';
    return result;
  }

  // 禁止词汇检查
  if (forbiddenWords.length > 0) {
    const hasForbiddenWords = forbiddenWords.some(word => 
      password.toLowerCase().includes(word.toLowerCase())
    );
    
    if (hasForbiddenWords) {
      result.details.hasForbiddenWords = true;
      score -= 20;
    }
  }

  // 自定义模式检查
  if (customPattern) {
    if (customPattern.test(password)) {
      result.details.matchesCustomPattern = true;
      score += 10;
    }
  }

  // 复杂度检查
  const uniqueChars = new Set(password).size;
  score += Math.min(uniqueChars * 2, 20);

  // 确定密码强度等级
  if (score < 30) {
    result.level = PASSWORD_LEVELS.WEAK;
  } else if (score < 50) {
    result.level = PASSWORD_LEVELS.MEDIUM;
  } else if (score < 70) {
    result.level = PASSWORD_LEVELS.STRONG;
  } else {
    result.level = PASSWORD_LEVELS.VERY_STRONG;
  }

  result.score = Math.max(0, Math.min(100, score));

  return result;
}

/**
 * 验证银行卡号
 * @param {string} cardNumber - 银行卡号
 * @param {string} cardType - 银行卡类型
 * @returns {BankCardResult} 验证结果
 */
export function validateBankCard(cardNumber: string, cardType: string = 'unknown'): BankCardResult {
  if (!cardNumber || typeof cardNumber !== 'string') {
    return {
      isValid: false,
      message: '银行卡号不能为空',
      cardType: cardType
    };
  }

  const cleanCardNumber = cardNumber.replace(/\s/g, '');
  
  if (!/^\d{13,19}$/.test(cleanCardNumber)) {
    return {
      isValid: false,
      message: '银行卡号格式不正确',
      cardType: cardType
    };
  }

  // Luhn算法验证
  if (!validateLuhnAlgorithm(cleanCardNumber)) {
    return {
      isValid: false,
      message: '银行卡号校验失败',
      cardType: cardType
    };
  }

  // 识别银行卡类型
  const detectedType = detectBankCardType(cleanCardNumber);
  
  return {
    isValid: true,
    message: '银行卡号有效',
    cardType: detectedType,
    maskedNumber: maskBankCard(cleanCardNumber)
  };
}

/**
 * Luhn算法验证
 * @param {string} cardNumber - 银行卡号
 * @returns {boolean} 是否有效
 */
export function validateLuhnAlgorithm(cardNumber: string): boolean {
  let sum = 0;
  let isEven = false;
  
  for (let i = cardNumber.length - 1; i >= 0; i--) {
    let digit = parseInt(cardNumber.charAt(i));
    
    if (isEven) {
      digit *= 2;
      if (digit > 9) {
        digit -= 9;
      }
    }
    
    sum += digit;
    isEven = !isEven;
  }
  
  return sum % 10 === 0;
}

/**
 * 识别银行卡类型
 * @param {string} cardNumber - 银行卡号
 * @returns {string} 银行卡类型
 */
export function detectBankCardType(cardNumber: string): string {
  const patterns: Record<string, RegExp> = {
    'Visa': /^4[0-9]{12}(?:[0-9]{3})?$/,
    'MasterCard': /^5[1-5][0-9]{14}$/,
    'American Express': /^3[47][0-9]{13}$/,
    'Discover': /^6(?:011|5[0-9]{2})[0-9]{12}$/,
    'JCB': /^(?:2131|1800|35\d{3})\d{11}$/,
    'Diners Club': /^3[0689][0-9]{12}$/,
    'UnionPay': /^62[0-9]{14,17}$/,
    '中国银行': /^4[0-9]{12}(?:[0-9]{3})?$/,
    '工商银行': /^6222[0-9]{12}$/,
    '建设银行': /^6227[0-9]{12}$/,
    '农业银行': /^6228[0-9]{12}$/
  };
  
  for (const [type, pattern] of Object.entries(patterns)) {
    if (pattern.test(cardNumber)) {
      return type;
    }
  }
  
  return 'unknown';
}

/**
 * 银行卡号脱敏
 * @param {string} cardNumber - 银行卡号
 * @returns {string} 脱敏后的银行卡号
 */
export function maskBankCard(cardNumber: string): string {
  if (cardNumber.length < 8) return cardNumber;
  
  const start = cardNumber.substring(0, 4);
  const end = cardNumber.substring(cardNumber.length - 4);
  const middle = '*'.repeat(cardNumber.length - 8);
  
  return start + middle + end;
}

/**
 * 验证手机号
 * @param {string} phone - 手机号
 * @param {string} country - 国家代码
 * @returns {PhoneResult} 验证结果
 */
export function validatePhone(phone: string, country: string = 'CN'): PhoneResult {
  if (!phone || typeof phone !== 'string') {
    return {
      isValid: false,
      message: '手机号不能为空',
      country: country
    };
  }

  const cleanPhone = phone.replace(/\s/g, '');
  
  const patterns: Record<string, RegExp> = {
    'CN': /^1[3-9]\d{9}$/,
    'US': /^\+?1[2-9]\d{2}[2-9]\d{6}$/,
    'UK': /^\+?44\d{10}$/,
    'JP': /^\+?81[789]\d{8}$/,
    'KR': /^\+?82[1-9]\d{7,8}$/,
    'SG': /^\+?65[689]\d{7}$/,
    'HK': /^\+?852[569]\d{7}$/,
    'TW': /^\+?886[9]\d{8}$/
  };
  
  const pattern = patterns[country] || patterns['CN'];
  
  if (!pattern.test(cleanPhone)) {
    return {
      isValid: false,
      message: `手机号格式不正确（${country}）`,
      country: country
    };
  }
  
  return {
    isValid: true,
    message: '手机号有效',
    country: country,
    formatted: formatPhone(cleanPhone, country)
  };
}

/**
 * 格式化手机号
 * @param {string} phone - 手机号
 * @param {string} country - 国家代码
 * @returns {string} 格式化后的手机号
 */
export function formatPhone(phone: string, country: string = 'CN'): string {
  const cleanPhone = phone.replace(/\s/g, '');
  
  switch (country) {
    case 'CN':
      return cleanPhone.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3');
    case 'US':
      return cleanPhone.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
    default:
      return cleanPhone;
  }
}

/**
 * 验证邮箱
 * @param {string} email - 邮箱地址
 * @returns {EmailResult} 验证结果
 */
export function validateEmail(email: string): EmailResult {
  if (!email || typeof email !== 'string') {
    return {
      isValid: false,
      message: '邮箱地址不能为空'
    };
  }

  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  
  if (!emailRegex.test(email)) {
    return {
      isValid: false,
      message: '邮箱地址格式不正确'
    };
  }
  
  return {
    isValid: true,
    message: '邮箱地址有效',
    domain: email.split('@')[1]
  };
}

/**
 * 验证URL
 * @param {string} url - URL地址
 * @returns {UrlResult} 验证结果
 */
export function validateUrl(url: string): UrlResult {
  if (!url || typeof url !== 'string') {
    return {
      isValid: false,
      message: 'URL不能为空'
    };
  }

  try {
    const urlObj = new URL(url);
    
    return {
      isValid: true,
      message: 'URL有效',
      protocol: urlObj.protocol,
      hostname: urlObj.hostname,
      pathname: urlObj.pathname
    };
  } catch (error) {
    return {
      isValid: false,
      message: 'URL格式不正确'
    };
  }
}

/**
 * 验证IP地址
 * @param {string} ip - IP地址
 * @param {string} version - IP版本
 * @returns {IpResult} 验证结果
 */
export function validateIp(ip: string, version: string = 'both'): IpResult {
  if (!ip || typeof ip !== 'string') {
    return {
      isValid: false,
      message: 'IP地址不能为空',
      version: version
    };
  }

  const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
  const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
  
  let isValid = false;
  let detectedVersion = '';
  
  if (version === 'both' || version === 'ipv4') {
    if (ipv4Regex.test(ip)) {
      isValid = true;
      detectedVersion = 'IPv4';
    }
  }
  
  if (!isValid && (version === 'both' || version === 'ipv6')) {
    if (ipv6Regex.test(ip)) {
      isValid = true;
      detectedVersion = 'IPv6';
    }
  }
  
  return {
    isValid: isValid,
    message: isValid ? 'IP地址有效' : 'IP地址格式不正确',
    version: detectedVersion
  };
}

/**
 * 验证邮政编码
 * @param {string} postalCode - 邮政编码
 * @param {string} country - 国家代码
 * @returns {PostalCodeResult} 验证结果
 */
export function validatePostalCode(postalCode: string, country: string = 'CN'): PostalCodeResult {
  if (!postalCode || typeof postalCode !== 'string') {
    return {
      isValid: false,
      message: '邮政编码不能为空',
      country: country
    };
  }

  const patterns: Record<string, RegExp> = {
    'CN': /^[1-9]\d{5}$/,
    'US': /^\d{5}(-\d{4})?$/,
    'UK': /^[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}$/i,
    'JP': /^\d{3}-\d{4}$/,
    'CA': /^[A-Z]\d[A-Z]\s?\d[A-Z]\d$/i,
    'DE': /^\d{5}$/,
    'FR': /^\d{5}$/,
    'AU': /^\d{4}$/
  };
  
  const pattern = patterns[country] || patterns['CN'];
  
  if (!pattern.test(postalCode)) {
    return {
      isValid: false,
      message: `邮政编码格式不正确（${country}）`,
      country: country
    };
  }
  
  return {
    isValid: true,
    message: '邮政编码有效',
    country: country
  };
}

/**
 * 验证车牌号
 * @param {string} licensePlate - 车牌号
 * @param {string} country - 国家代码
 * @returns {LicensePlateResult} 验证结果
 */
export function validateLicensePlate(licensePlate: string, country: string = 'CN'): LicensePlateResult {
  if (!licensePlate || typeof licensePlate !== 'string') {
    return {
      isValid: false,
      message: '车牌号不能为空',
      country: country
    };
  }

  const patterns: Record<string, RegExp> = {
    'CN': /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/,
    'US': /^[A-Z]{3}\s?[0-9]{4}$/,
    'UK': /^[A-Z]{2}\d{2}\s?[A-Z]{3}$/,
    'JP': /^[A-Z]{2}\d{3}-[A-Z]{2}$/,
    'KR': /^[0-9]{2,3}[가-힣][0-9]{4}$/,
    'SG': /^[A-Z]{2}\d{4}[A-Z]$/,
    'HK': /^[A-Z]{2}\d{4}$/,
    'TW': /^[A-Z]{2}[0-9]{4}$/
  };
  
  const pattern = patterns[country] || patterns['CN'];
  
  if (!pattern.test(licensePlate)) {
    return {
      isValid: false,
      message: `车牌号格式不正确（${country}）`,
      country: country
    };
  }
  
  return {
    isValid: true,
    message: '车牌号有效',
    country: country
  };
}

/**
 * 批量验证数据
 * @param {Array} data - 验证数据数组
 * @param {string} type - 验证类型
 * @returns {BatchValidationResult} 批量验证结果
 */
export function validateBatch(data: any[], type: string): BatchValidationResult {
  if (!Array.isArray(data)) {
    return {
      isValid: false,
      message: '验证数据必须是数组',
      totalCount: 0,
      validCount: 0,
      invalidCount: 0,
      results: []
    };
  }

  const results: Array<{index: number; value: any; result: ValidationResult}> = [];
  let validCount = 0;
  let invalidCount = 0;

  for (let i = 0; i < data.length; i++) {
    let result: ValidationResult;
    
    switch (type) {
      case VALIDATION_TYPES.ID_CARD:
        result = validateIdCard(data[i]);
        break;
      case VALIDATION_TYPES.PASSWORD:
        result = validatePassword(data[i]);
        break;
      case VALIDATION_TYPES.BANK_CARD:
        result = validateBankCard(data[i]);
        break;
      case VALIDATION_TYPES.PHONE:
        result = validatePhone(data[i]);
        break;
      case VALIDATION_TYPES.EMAIL:
        result = validateEmail(data[i]);
        break;
      case VALIDATION_TYPES.URL:
        result = validateUrl(data[i]);
        break;
      case VALIDATION_TYPES.IP:
        result = validateIp(data[i]);
        break;
      case VALIDATION_TYPES.POSTAL_CODE:
        result = validatePostalCode(data[i]);
        break;
      case VALIDATION_TYPES.LICENSE_PLATE:
        result = validateLicensePlate(data[i]);
        break;
      default:
        result = {
          isValid: false,
          message: '不支持的验证类型'
        };
    }
    
    results.push({
      index: i,
      value: data[i],
      result: result
    });
    
    if (result.isValid) {
      validCount++;
    } else {
      invalidCount++;
    }
  }

  return {
    isValid: validCount === data.length,
    message: `验证完成：${validCount}个有效，${invalidCount}个无效`,
    totalCount: data.length,
    validCount: validCount,
    invalidCount: invalidCount,
    results: results
  };
}
